﻿using System;
using System.Collections.Generic;
#if DEBUG
using System.Diagnostics;
#endif // #if DEBUG
using System.Linq;
using System.Text;
using System.Data.Objects.DataClasses;
using System.Xml;

using FRL.DebtChased.Extensions;

namespace FRL.DebtChased.Repository
{

	/// <summary>
	/// Extensions to the ClientCollectorAssignments model
	/// </summary>
	public partial class ClientCollectorAssignments
	{

		/////////////////////////////////////////////////////////////
		// Constants and Enumerations

		public const decimal MaximumDecimalCode = -1;

		/////////////////////////////////////////////////////////////
		// Static Operations

		public static void ChooseCollectorId(DebtChasedEntities ent, int iClientId, decimal dcTotalAmount, out int? iCollectorId, out int? iManagerId )
		{

			// Reset function parameters
			iCollectorId = null;
			iManagerId = null;

			// TODO
			// This has all changed, review with FRL
			/*
			// Load collectors from the table FOR THIS CLIENT
			List<int> iCollectorIds = (from cca in ent.ClientCollectorAssignments
									   where 
									   (
										(cca.ClientId==iClientId)
										&&
										(
											(dcTotalAmount >= cca.Min)
											&&
											(
												(cca.Max==MaximumDecimalCode)
												||
												(dcTotalAmount <= cca.Max)
											)
										)
									   )
									   select cca.UserId).ToList();

			// If no collectors found...
			if (iCollectorIds.Count == 0)
			{

				// Load DEFAULT collectors from the table
				iCollectorIds = (from cca in ent.ClientCollectorAssignments
								 where
								 (
									(cca.ClientId == null)
									&&
									(
										(dcTotalAmount >= cca.Min)
										&&
										(
											(cca.Max == MaximumDecimalCode)
											||
											(dcTotalAmount <= cca.Max)
										)
									)
								 )
								 select cca.UserId).ToList();

			}

			// Choose a collector id
			if(iCollectorIds.Count==1)
				iCollectorId = iCollectorIds[0];
			else if(iCollectorIds.Count>1)
			{
				Random rnd = new Random();
				iCollectorId = iCollectorIds[rnd.Next(iCollectorIds.Count)];
			}

			// If collector found...
			if (iCollectorId != null)
			{

				// Get the collectors manager
				int iTemp = iCollectorId.Value;
				iManagerId = (from u in ent.Users
							 where (u.UserId == iTemp)
							 select u.ParentUserId).FirstOrDefault();
#if DEBUG
				Debug.Assert(iManagerId != null);
#endif // #if DEBUG

			}
			 */

		}

	}

}
